package org.example.controller;

import feign.Feign;
import feign.RequestInterceptor;
import org.example.controller.feign.FeignService;
import org.example.controller.feign.HttpFeignService;
import org.example.controller.feign.NativeFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/test")
@CrossOrigin
public class TestController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private FeignService feignService;

    @Autowired
    private HttpFeignService httpFeignService;

    /**
     * 根据服务名检查实例是否存在
     * */
    @RequestMapping("/c1")
    public String c1(){

        //服务名
        String server_name = "eureka-product";

        //根据服务名获取实例
        List<ServiceInstance> instances = discoveryClient.getInstances(server_name);

        //获取第一个实例
        ServiceInstance serviceInstance = instances.get(0);

        return "success";
    }

    @RequestMapping("/c2")
    public String c2(){

        //服务名
        String server_name = "eureka-product";

        //组装请求  这里一个巨坑：@LoadBalanced RestTemplate	严格（推荐连字符）	统一改为 eureka-product
        ResponseEntity<String> forEntity = restTemplate.getForEntity("http://"+ server_name +"/product/test/i1", String.class, new HashMap<>());
        System.out.println( "调用服务结果：" + forEntity.getBody());
        return forEntity.getBody();
    }

    @RequestMapping("/c3")
    public String c3(){
        String test = feignService.test();
        System.out.println("通过 openFeign 调用：" + test);
        return test;
    }

    @RequestMapping("/c4")
    public String c4(){
        String test = httpFeignService.test();
        System.out.println("通过 openFeign 调用 http 请求：" + test);
        return test;
    }

    @Autowired
    private RequestInterceptor requestInterceptor;

    /**
     * 原生 Feign 的使用
     * */
    @RequestMapping("/c5")
    public String c5(){
        Feign.Builder builder = Feign.builder();
        builder = builder.requestInterceptor(requestInterceptor);
        NativeFeignService target = builder.target(NativeFeignService.class, "http://localhost:10004/product/test");
        String s = target.test();
        System.out.println("通过原生 Feign 调用接口：" + s);
        return s;
    }
}
